<template>
	<view class="drawer-container">
        <!-- <uni-nav-bar left-icon="back" left-text="返回" title="选择商品" @clickLeft="onClickLeft"></uni-nav-bar> -->
        <view class="header-wrapper">
            <header-bar :config="config"></header-bar>
        </view>
	    <view class="custom-content" :style="customStyle">  
	        <search-box
	            placeholderText="请输入商品名称/编码/型号"
	            :searchValue="productSearchVal"
	            @changeSearchVal="changeSearchVal"
	            @searchFn="searchFn" />
            <view class="main-dom product-main">
                <scroll-view class="product-main-nav" scroll-y="true" :style="{ height: listHeight }">
                    <nav-tree
                        :tree-data="classifyList"
                        :tagId="tagId"
                        :active-id="activeId"
                        @treeClickEvent="treeClickEvent">
                    </nav-tree>
                </scroll-view>
                <view :class="isIOS?'product-main-list content-wrapper content-wrapper-ios':'product-main-list content-wrapper'">
                    <view class="flex checkAll">
                        <radio-group @change="changeCheck">
                            <radio style="transform: scale(0.8)" class="uni-radio-wrapper" value="invert" >反选</radio>
                            <radio style="transform: scale(0.8)" class="uni-radio-wrapper" value="checkAll">全选</radio>
                        </radio-group>
                    </view>
                    <mescroll-uni
                        ref="mescrollRef"
                        @init="mescrollInit"
                        :fixed="false"
                        :up="upOption"
                        @down="downRefresh"
                        @up="getNewData">
                        <checkbox-group @change="checkboxChange">
                            <label class="content-item" v-for="item in productList" :key="String(item.FID)">
                                <view class="">
								<view style="word-break: break-all;">{{ item.FNAME }}</view>
                                <view class="code">编码：{{item.FNUMBER}}</view>
                                <view class="code">组织：{{item.OrgName}}</view>
                                <view class="code">分组：{{item.FGROUPName}}</view>
                                </view>
                                <checkbox
                                    :value="String(item.FID)"
                                    :checked="item.isSelected"
                                    style="transform: scale(0.7)" />
                            </label>
                        </checkbox-group>
                    </mescroll-uni>
                    <view :class="isIOS?'apple-style bottom-wrapper':'bottom-wrapper'">
                        <view class="reset-btn flex-center" @click="handleResetP">重置</view>
                        <view class="sure-btn flex-center" @click="handleSureP">确认</view>
                    </view>
                    <view @click="goHome()" class="returnHome">返回<br/>首页</view>
                </view>
           </view>
        </view>
	</view>
 
</template>

<script>
import { setReduce } from "@/utils/utils.js"
import { GetGood,GetGoodGroup} from "@/service/api/erp.js"
import navTree from "@/pages/components/product/nav-tree.vue"
export default {
    components: {      
        navTree,
    },
	props: {
	    productSelectData: {
	        type: Object,
	        default: {},
	    },
        productTagId: {
            type: String,
            default: "",
        },
        color: {
        	type: String,
        	default: "#000000"
        },
        leftIcon: {
        	type: String,
        	default: ""
        },
        backgroundColor: {
        	type: String,
        	default: "#FFFFFF"
        },
	},
    data() {
        return {
            pageNumber: 1,
            pageSize: 20,
			productSearchVal:'',
			productList:[],
			selectedWarehouse:[],
			params:[],            
            classifyList: [],
            tagId: "",
            activeId: "-1",
            leftPageNumber: 1,
            leftpageSize: 999,
            fullName: "",
            code: "",
            FNAME: "",
            FPARENTID: "",
            plist: [],  
            allCheck: {
                name: "全选",
                value: "all",
                checked: false,
            },
            config: {
                title: "选择商品",
                centerSlot: true,
                rightSlot: false,
				backPage: "/pages/stock/index",
            },
            isIOS: false,
        }
    },
	
    computed: {
		customStyle() {
		    return {  
		        height: this.isIOS ? '100%' : `calc(100% - 85rpx)`,  
		    };  
		},  
    },
	watch:{       
        productTagId(e) {
            if (e) {
                this.tagId = e
                this.tagloading(e)
            }
        },
        classifyID(ID) {
                if (ID) {
                    this.classifyList.forEach((res) => {
                        if (res.id == ID) {
                            res.expand = true
                            this.treeClickEvent(res)
                            return
                        } else {
                            res.expand = false
                            if (res.children) {
                                res.children.forEach((sub) => {
                                    if (sub.id == ID) {
                                        res.expand = true
                                        this.treeClickEvent(res)
                                        setTimeout((time) => {
                                            sub.expand = true
                                            this.treeClickEvent(sub)
                                            this.$forceUpdate()
                                        }, 500)
                                        return
                                    } else {
                                        if (sub.children.length > 0) {
                                            sub.children.forEach((three) => {
                                                if (three.id == ID) {
                                                    res.expand = true
                                                    this.treeClickEvent(res)
                                                    setTimeout((time) => {
                                                        sub.expand = true
                                                        this.treeClickEvent(sub)
                                                    }, 500)
                                                    setTimeout((time) => {
                                                        three.expand = true
                                                        this.treeClickEvent(three)
                                                        this.$forceUpdate()
                                                    }, 1000)
                                                    return
                                                }
                                            })
                                        }
                                    }
                                })
                            }
                        }
                    })
                }
            },
	},
    created() {
        this.tagloading()
    },
    mounted() {
        this.detectPlatform();  
        this.tagId = this.productTagId
        uni.$on("resetStockWarehouse", this.downRefresh)
    },
    unmounted() {
        uni.$off("resetStockWarehouse", this.downRefresh)
    },
    methods: {
        detectPlatform() {  
          const systemInfo = uni.getSystemInfoSync();  
          this.isIOS = systemInfo.platform.toLowerCase().indexOf('ios') !== -1;  
        },  
        searchFn(val) {
			this.productList = []
            this.changeSearchVal(val)
            this.mescroll.scrollTo(0, 0)
            this.mescroll.resetUpScroll()
        },
        checkboxChange(e) {
            const selectedWarehouse = this.productList.filter((item) => e.detail.value.includes(item.FID))
            console.log(12)
            console.log(selectedWarehouse)
            console.log(e.detail.value)
			this.selectedWarehouse = selectedWarehouse;
			let params = []
			this.selectedWarehouse.forEach((item) => {
				params.push(item.FNUMBER)
			})
            this.productList.forEach(item => {  
                item.isSelected = e.detail.value.includes(String(item.FID));  
            });  
            this.productSelectData = this.selectedWarehouse
			this.params = params;
			console.log(params)
        },
		handleResetP(){
			this.selectedWarehouse = [];
			this.params = [];
			this.productList = []
			this.downRefresh()
			this.$emit('handleResetP')
		},
		handleSureP(){
			this.$emit('handleSureP',this.selectedWarehouse,this.params)
		},
        changeSearchVal(val) {
            this.productSearchVal = val
        },
        getCustomList() {
            const params = {
                pageNumber: this.pageNumber,
                pageSize: this.pageSize,
                fullName: this.productSearchVal,
                code: this.code
            }
            GetGood(params).then((res) => {
                if (res.State == 1) {
                    this.mescroll.endByPage(res.Data.length, res.TotalAmout)
					this.productList = this.productList.concat(res.Data)
					let selectedWarehouse = []
					this.productList.forEach((item) => {
						this.$set(item, "isSelected", false)
						this.productSelectData.forEach((subitem) =>{
							if(subitem.FNUMBER==item.FNUMBER && subitem.FID==item.FID){
								this.$set(item, "isSelected", true)
								selectedWarehouse.push(item)
							}
						})
						this.selectedWarehouse = selectedWarehouse;
						let params = []
						this.selectedWarehouse.forEach((item) => {
							params.push(item.FNUMBER)
						})
						this.params = params;
					})
                } else {
                    this.mescroll.endErr()
                }
            })
        },
        // 上拉加载
        getNewData(page) {
            this.pageNumber = page.num
            this.getCustomList()
        },
        // 下拉刷新
        downRefresh() {
            this.mescroll.scrollTo(0, 0)
            this.mescroll.resetUpScroll()
        },
        tagloading(e) {
            let param = {
                pageSize: this.leftpageSize,
                pageNumber:this.leftPageNumber,
                fullName: this.fullName,
            }
            GetGoodGroup(param).then((res) => {
                this.initClassify = false
                if (res.Data && res.Data.length > 0) {
                    this.classifyList = []
                    if(res.Data[0].FPARENTID === "0"){
                        this.classifyList = [{FNAME:"全部",FID:"-1"}]
                    }else{
                        const cate = this.plist[this.plist.length - 1]
                        let PFID = "0"
                        if(this.plist[this.plist.length - 2] >= 0){
                            PFID = this.plist[this.plist.length - 2].FID
                        }else{
                            PFID = this.plist[this.plist.length - 1].FPARENTID
                        }
                        this.classifyList = [{FNAME:"返回上级",FID: PFID },{FNAME:cate.FNAME,FID:cate.FID,FPARENTID:cate.FPARENTID}]
                    }                    
                    res.Data.forEach((item) => {
                        this.classifyList.push(item)
                    })
                }
                
            })
        },
        // 点击分类事件
        treeClickEvent(item) {
            this.activeId = item.FID
            this.FPARENTID = item.FPARENTID
            this.fullName = item.FID
            this.code = item.FID
            if(item.FNAME === "返回上级"){
                this.plist.pop()
                if(this.plist.length > 0){
                    this.activeId = this.plist[this.plist.length - 1].FID
                    this.fullName = this.plist[this.plist.length - 1].FID
                    this.code = this.plist[this.plist.length - 1].FID
                }else{
                    this.fullName  =  ""
                    this.code = ""
                    this.activeId  = "-1"
                }
            }
            if(item.LowerIds &&  item.LowerIds !== ""){
                const obj = {}
                obj.FPARENTID = item.FPARENTID
                obj.FNAME = item.FNAME
                obj.FID = item.FID
                this.plist.push(obj)
            }         
            console.log(this.activeId,item,this.plist,"sss")
            // if (this.activeId !== item.FID) {
            //     this.resetClass(item)
            // }else{
                this.tagloading()
            // }
            this.pageNumber = 1
            this.pageSize = 20
            this.productList = []
            this.getCustomList()
        },
        resetClass(item, bool = true) {
            const that = this
            if (bool) {
                that.secondClassifyList = item.children || []
                that.isFold = true
            } else {
                if (item.children && item.children.length > 0) {
                    that.secondClassifyList = item.children
                    that.isFold = true
                }
            }
            that.activeId = item.FID
            
            that.$nextTick(function () {
                that.getClassifyHeight()
            })
            // that.refresh()
        },
        getClassifyHeight() {
            if (this.secondClassifyList && this.secondClassifyList.length > 0) {
                const query = uni.createSelectorQuery().in(this)
                query
                    .select(".secondClassify")
                    .boundingClientRect((data) => {
                        let dataHeight = 0
                        if (data) {
                            dataHeight = Number(data.height)
                        }
                        this.listHeight1 = Number(this.initHeight) - dataHeight - 62 + "px"
                    })
                    .exec()
            } else {
                this.listHeight1 = this.listHeightNoneSub
            }
        },
        changeCheck(e) {  
            // 全选  
            if (e.detail.value === "checkAll") {  
                this.selectedWarehouse = [...this.productList]; // 复制整个列表到selectedWarehouse  
                this.productList.forEach(item => this.$set(item, "isSelected", true)); // 设置每个项目为已选择               
            }  
            // 反选  
            else if (e.detail.value === "invert") { // 假设 e.detail.value 为 "invert" 时表示反选  
                this.productList.forEach(item => {  
                    // 切换当前项的选择状态  
                    this.$set(item, "isSelected", !item.isSelected);  
                      
                    // 更新 selectedWarehouse  
                    const isInSelectedWarehouse = this.selectedWarehouse.some(selected => selected.FID === item.FID);  
                    if (item.isSelected && !isInSelectedWarehouse) {  
                        this.selectedWarehouse.push(item);  
                    } else if (!item.isSelected && isInSelectedWarehouse) {  
                        const index = this.selectedWarehouse.findIndex(selected => selected.FID === item.FID);  
                        if (index > -1) {  
                            this.selectedWarehouse.splice(index, 1);  
                        }  
                    }  
                });  
            }  
            // 其他情况（可能是单选或取消选择）  
            else {  
                // 这里处理单选或取消选择的逻辑  
                // ...
            }  
          
            // 构造 params 数组  
            let params = this.selectedWarehouse.map(item => item.FNUMBER);  
            this.productSelectData = this.selectedWarehouse
            this.params = params;  
            console.log(e, this.selectedWarehouse, "选择");  
        },
        onClickLeft() {
        	this.$emit("handleSureP");
        },
        goHome(){
            this.fullName = ""
            this.code = ""
            this.pageNumber = 1
            this.pageSize = 20
            this.leftPageNumber = 1
            this.leftpageSize = 999
            this.productList = []            
            this.tagloading()
            this.getCustomList()
        }
    },
}
</script>

<style lang="scss" scoped>    
	.drawer-container {
	    position: relative;
	    width: 100%;
	    height: 100%;
	    box-sizing: border-box;
	    background-color: $color-white;
	    color: $color-gray-1;
	
	    .bottom-wrapper {
	        position: absolute;
	        left: 0;
	        right: 0;
	        bottom: -60rpx;
	        z-index: 999;
	        height: 72rpx;
	        display: flex;
	        font-size: 28rpx;
	
	        view {
	            flex: 1;
	        }
	
	        .reset-btn {
	            background-color: $color-white;
	            border-top: 1rpx solid #f0f0f0;
	        }
	
	        .sure-btn {
	            background-color: $app-color-main;
	            color: $color-white;
	        }
	    }
		.apple-style{
			bottom: 120rpx;
		}
	}
.custom-content {
    // height: calc(100% - 85rpx);
    // padding-top: 88rpx;
	padding-bottom: 90rpx;
	box-sizing: border-box;
	overflow: hidden;
    .content-wrapper {
       height: calc(100% - 200rpx);
       padding-bottom: 120rpx;
        .content-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 28rpx;
            min-height: 78rpx;
            margin-left: 28rpx;
            margin-right: 24rpx;
            border-bottom: 1rpx solid $uni-border-bottom-color;
        }
		.code{
			font-size: 24rpx;
			color: #999;
		}
        ::v-deep uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked:before {
            color: $app-color-main;
        }

        ::v-deep uni-checkbox:not([disabled]) .uni-checkbox-input:hover {
            border-color: $app-color-main;
        }
    }
	.content-wrapper-ios{
		height: calc(100% - 200rpx);
		       padding-bottom: 200rpx;
	}
}
.product-main {
    display: flex;
    flex-direction: row;
    height: calc(100% - 100rpx);

    .product-main-nav {
        display: flex;
        flex: 1.3;
        flex-direction: column;
        background: $uni-bg-color-grey;
        position: relative;
        z-index: 10;
        overflow-y: scroll;
    }

    .product-main-list {
        // display: flex;
        flex: 3.5;
        // justify-content: center;
        position: relative;
        z-index: 1;
        margin-left: -8rpx;
    }

    .p-b-120 {
        padding-bottom: 120rpx;
    }
}
.checkAll{
    justify-content: flex-end;
    margin-right: 100rpx;
    margin-bottom: 20rpx;
}
.uni-radio-wrapper{
    margin-left: 40rpx;
    font-size: 28rpx;
}

.returnHome{
	position: fixed;
	bottom: 124rpx;
	right:24rpx;
	width: 80rpx;
	height: 80rpx;
	background: #FFFFFF;
	box-shadow: 0px 0px 16px 0px rgba(0,0,0,0.2);
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 24rpx;
	color: #333;
	border-radius: 50%;
}
</style>
